package cn.edu.szpt.qqdemov3.widgets;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.util.AttributeSet;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatImageView;

import cn.edu.szpt.qqdemov3.R;

public class MyCircleImageView extends AppCompatImageView {
    private int mBorderWidth ;
    private int mBorderColor ;

    public MyCircleImageView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        TypedArray  a = context.obtainStyledAttributes(attrs, R.styleable.MyCircleImageViewAttrs);
        mBorderColor= a.getColor(R.styleable.MyCircleImageViewAttrs_border_color,Color.parseColor("#f2f2f2"));
        float density= context.getResources().getDisplayMetrics().density;
        mBorderWidth = a.getDimensionPixelSize(R.styleable.MyCircleImageViewAttrs_border_width,(int)(5*density));
        a.recycle();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        int view_width = getWidth();
        int view_height = getHeight();
        int layer = canvas.saveLayer(0,0,view_width,view_height,null);

        //绘制控件中指定的图片，作为目标图像
        super.onDraw(canvas);
        //生成圆形蒙版
        Bitmap mask = getMaskBitmap(view_width,view_height);
        //设置图像混合模式为DSTIN
        Paint paint = new Paint();
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
        paint.setStyle(Paint.Style.FILL);
        paint.setAntiAlias(true);

        //使用DSTIN混合模式绘制蒙版图像（源图像）
        canvas.drawBitmap(mask,0,0,paint);

        canvas.restoreToCount(layer);
        drawBorder(canvas,view_width,view_height);
    }

    private Bitmap getMaskBitmap(int width,int height){
        Bitmap bmp = Bitmap.createBitmap(width,height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bmp);
        canvas.drawCircle(width/2,height/2,Math.min(width,height)/2,new Paint());
        return bmp;
    }

    private void drawBorder(Canvas canvas,int width,int height){
        if(mBorderWidth==0){
            return;
        }
        Paint paint = new Paint();
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(mBorderWidth);
        paint.setColor(mBorderColor);
        paint.setAntiAlias(true);
        canvas.drawCircle(width/2,height/2,(Math.min(width,height)-mBorderWidth)/2,paint);
    }
}
